package com.lxb.eduorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxb.commonutils.JwtUtils;
import com.lxb.commonutils.R;
import com.lxb.eduorder.entity.Order;
import com.lxb.eduorder.service.OrderService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * 订单 前端控制器
 *
 * @author lixuebin
 * @since 2023-01-16
 */
@Api(description = "订单控制层")
@RestController
@RequestMapping("/eduOrder/order")
//@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     *
     * @param courseId 课程id
     * @param request
     * @return 返回订单id
     */
    @PostMapping("/createOrder/{courseId}")
    public R save(@PathVariable String courseId, HttpServletRequest request) {
        //根据课程id和用户id创建订单，返回订单id
        String orderId = orderService.save(courseId, JwtUtils.getMemberIdByJwtToken(request));
        return R.ok().data("orderId", orderId);
    }

    /**
     * 根据订单id，获取订单信息
     *
     * @param orderId
     * @return
     */
    @GetMapping("/getOrder/{orderId}")
    public R getOrder(@PathVariable("orderId") String orderId) {
        QueryWrapper<Order> wrapper = new QueryWrapper();
        wrapper.eq("order_no", orderId);
        Order order = orderService.getOne(wrapper);
        //返回订单信息
        return R.ok().data("item", order);
    }

    /**
     * 查询某个用户是否购买课程
     *
     * @param courseId
     * @param memberId
     * @return
     */
    @GetMapping("/isBuyCourse/{courseId}/{memberId}")
    public boolean isByCourse(@PathVariable("courseId") String courseId, @PathVariable("memberId") String memberId) {

        QueryWrapper<Order> wrapper = new QueryWrapper<Order>().eq("course_id", courseId).eq("member_id", memberId)
                .eq("status",1);

        int count = orderService.count(wrapper);

        return count>0  ? true:false;
    }
}

